package com.slipper.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Visual {
    public static String[] parseFileId(String json) {
        if (Tool.isBlank(json)) return null;

        List<String> resultList = new ArrayList<>();
        parseItem(JSONObject.parseObject(json), resultList);
        return resultList.stream().filter(Tool::isNotBlank).toList().toArray(new String[0]);
    }

    public static void parseItem(JSONObject jsonObject, List<String> resultList) {
        if (jsonObject == null) return;

        JSONArray styleList = jsonObject.getJSONArray("styleList");
        if (styleList != null && !styleList.isEmpty()) {
            styleList.forEach(item -> {
                JSONObject style = ((JSONObject) item).getJSONObject("style");
                if (style != null
                        && "图片".equals(style.getString("bgMode"))
                        && Tool.isNotBlank(style.getString("imageId"))) {
                    resultList.add(style.getString("imageId"));
                }

                JSONObject compStyle = ((JSONObject) item).getJSONObject("compStyle");
                if (compStyle != null
                        && "图片".equals(compStyle.getString("bgMode"))
                        && Tool.isNotBlank(compStyle.getString("imageId"))) {
                    resultList.add(compStyle.getString("imageId"));
                }

                if (compStyle != null && "image".equals(jsonObject.getString("type"))) {
                    if (Tool.isNotBlank(compStyle.getString("default"))) {
                        resultList.add(compStyle.getString("default"));
                    }
                }
            });
        }

        JSONArray children = jsonObject.getJSONArray("children");
        if (children != null && !children.isEmpty()) {
            children.forEach(item -> parseItem((JSONObject) item, resultList));
        }
    }
}
